package cn.wolfcode.orderServer.service.impl;

import cn.wolfcode.orderServer.domain.Order;
import cn.wolfcode.orderServer.feign.ProductFeignApi;
import cn.wolfcode.orderServer.repository.OrderRepository;
import cn.wolfcode.orderServer.service.IOrderService;
import cn.wolfcode.productServer.domain.Product;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

/**
 * @ClassName OrderServiceImpl
 * @Author VCR
 * @Date 2021/12/21 15:20
 * @Version 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private ProductFeignApi productFeignApi;        // 注入Feign组件

    @Override
    public Order get(Long productId, Long userId) {
        log.info("调用订单服务Service层");
        log.info("接收到{}号商品的下单请求,接下来调用商品微服务查询此商品信息", productId);
//        Product product = restTemplate.getForObject("http://localhost:8081/product/get?id=" + productId,Product.class);
        /*List<ServiceInstance> InstanceList = discoveryClient.getInstances("product-service");
        int nextInt = new Random().nextInt(InstanceList.size());
        ServiceInstance serviceInstance = InstanceList.get(nextInt);

        Product product = restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/get?id=" + productId, Product.class);*/

//        Product product = restTemplate.getForObject("http://product-service/product/get?id=" + productId, Product.class);
        Product product = productFeignApi.get(productId);

        Order order = new Order();
        order.setOid(1L);
        order.setNumber(1);
        order.setPid(productId);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setUid(userId);
        order.setUsername("avCoder");
        log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));
        return order;

    }
}
